package com.lmk.dsa.struct.commons;

import java.util.Objects;

/**
 * KV键值形式的数据节点
 * @param <K>   Key，需要实现Comparable接口
 * @param <V>   Value
 * @author LaoMake
 * @since 1.0
 */
public class KvNode<K extends Comparable<? super K>, V> implements Comparable{
    /** Key */
    public K key;

    /** Value */
    public V value;

    /** 是否只使用Key */
    protected boolean onlyKey = false;

    public KvNode() {
    }

    public KvNode(boolean onlyKey) {
        this.onlyKey = onlyKey;
    }

    public KvNode(K key) {
        this.key = key;
        this.onlyKey = true;
    }

    public KvNode(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public boolean isOnlyKey() {
        return onlyKey;
    }

    public void setOnlyKey(boolean onlyKey) {
        this.onlyKey = onlyKey;
    }

    @Override
    public String toString() {
        if(onlyKey){
            return String.valueOf(key);
        }else{
            StringBuilder sb = new StringBuilder();
            sb.append("{").append(key).append(": ").append(value).append("}");
            return sb.toString();
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        KvNode<K, V> node = (KvNode<K, V>) o;
        return Objects.equals(key, node.key);
    }

    @Override
    public int hashCode() {
        return Objects.hash(key);
    }


    @Override
    public int compareTo(Object o) {
        KvNode<K, V> node = (KvNode<K, V>) o;
        return this.key.compareTo(node.key);
    }
}
